<script setup lang="ts">
import type { StudentWordItem } from '@/api/types/student'
import NavBar from '@/components/NavBar/index.vue'
import { useStudyWords } from '@/composables/useStudyWords'
import { handleNextStep, LearningState } from '@/services/learningStateMachine'
import { useUnitStudyWordsStore } from '@/stores/modules/useUnitStudyWordsStore'
import { navigateBack } from '@/utils/navigation'
import { computed, onMounted, ref } from 'vue'
import CuttingContainer from './components/CuttingContainer.vue'
import WordCuttingSept1 from './components/WordCuttingSept1.vue'
import WordCuttingSept2 from './components/WordCuttingSept2.vue'

const unitStudyWordsStore = useUnitStudyWordsStore()
const isShowSelectWord = ref(false)

const {
  localWords,
  initStudyWords,
  updateWordClickNum,
  setActiveWord,
} = useStudyWords()

// 判断当前是否是6N组混合检查
const is6NGroupCheck = computed(() => {
  if (!unitStudyWordsStore.mixedGroups || unitStudyWordsStore.mixedGroups.length !== 6) {
    return false
  }

  const currentGroupIndex = unitStudyWordsStore.currentGroupIndex
  const lastGroupInMixed = unitStudyWordsStore.mixedGroups[unitStudyWordsStore.mixedGroups.length - 1]

  // 如果混合组有6个元素，且最后一个元素等于当前组索引，且当前组索引+1是6的倍数，则认为是6N组
  return unitStudyWordsStore.mixedGroups.length === 6
    && lastGroupInMixed === currentGroupIndex
    && (currentGroupIndex + 1) % 6 === 0
})

// 初始化本地数据
onMounted(() => {
  unitStudyWordsStore.updateStudyStartTime()
  initStudyWords(unitStudyWordsStore.groupWords)
})

function handleClickCard(item: StudentWordItem) {
  updateWordClickNum(item.wordId)
}

function handleWordActivate(wordId: string | number) {
  setActiveWord(wordId)
}

function handleOnFinish() {
  isShowSelectWord.value = true
}

function handleOnComplete() {
  // 根据是否是6N组混合检查，调用不同的状态
  if (is6NGroupCheck.value) {
    handleNextStep(LearningState.MIXED_GROUP_6N)
  }
  else {
    handleNextStep(LearningState.MIXED_GROUP)
  }
}
</script>

<template>
  <CuttingContainer>
    <NavBar :title="unitStudyWordsStore.mixedGroupTitle" @left-click="navigateBack" />
    <!-- 剪刀 -->
    <WordCuttingSept1
      v-if="!isShowSelectWord"
      :words="localWords"
      @click-card="handleClickCard"
      @activate="handleWordActivate"
      @on-finish="handleOnFinish"
    />
    <!-- 选择 -->
    <WordCuttingSept2
      v-else
      :words="localWords"
      @click-card="handleClickCard"
      @activate="handleWordActivate"
      @on-complete="handleOnComplete"
    />
  </CuttingContainer>
</template>
